//
//  HMComposeViewController.swift
//  GuoGuo
//
//  Created by 艾小新 on 16/8/15.
//  Copyright © 2016年 xiaoxin. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMComposeViewController: UIViewController {
    
    // toolBar是否要执行跟随键盘的动画
    lazy var isToolBarAnimation: Bool = true

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

    
    private func setupUI() {
        
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem( title: "返回", target: self, action: #selector(HMComposeViewController.fanhui))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItemBtn)
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleItemView
        
        // 添加发微博文字控件及约束
        view.addSubview(textView)
        textView.snp_makeConstraints { (make) in
            
            make.edges.equalTo(self.view)
        }
        
        view.addSubview(composeTabBar)
        composeTabBar.snp_makeConstraints { (make) in
            
            make.bottom.leading.trailing.equalTo(self.view)
            make.height.equalTo(40)
        }
        
        textView.addSubview(pictureView)
        pictureView.snp_makeConstraints { (make) in
            
            // 距离上面100，先固定宽高
            make.top.equalTo(100)
            make.size.equalTo(CGSizeMake(SCREENW - 20, SCREENW - 20))
            make.leading.equalTo(10)
            
        }
        pictureView.hidden = true
        // 监听键盘，移动ComposeTabBar
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HMComposeViewController.willChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil
        )
        
        // 监听表情按钮点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HMComposeViewController.emoticonButtonClick(_:)), name: HMEmoticonDidSelectedNotification, object: nil)
        
    }
    
    
    
    /// 表情按钮点击的通过触发的方法
    @objc private func emoticonButtonClick(noti: NSNotification) {
        // 取到表情模型
        let emoticon = noti.userInfo!["emoticon"]! as! HMEmoticon
        // 添加表情到textView里面
        textView.insertEmoticon(emoticon)
        
        // 以下代表抽取到:
        //        // 代表是图片表情
        //        if emoticon.type == "0" {
        //            // 0. 取到textView现有的属性文字
        //            let originalAttr = NSMutableAttributedString(attributedString: textView.attributedText)
        //
        //            // 1. 通过表情模型里面的图片名转成表情图片
        //            let image = UIImage(named: "\(emoticon.folderName!)/\(emoticon.png!)", inBundle: HMEmoticonTools.sharedTools.emoticonsBundle, compatibleWithTraitCollection: nil)
        //
        //            // 2. 将图片添加到 文字附件(NSTextAttachment)
        //            let textAttachment = NSTextAttachment()
        //            textAttachment.image = image
        //            let imageWH = textView.font!.lineHeight
        //            // 设置图片大小
        //            textAttachment.bounds = CGRectMake(0, -4, imageWH, imageWH)
        //
        //            // 3. 将上一步的 NSTextAttachment 添加到 NSAttributedString
        //            let attr = NSMutableAttributedString(attributedString: NSAttributedString(attachment: textAttachment))
        //            // 指定表情图片对应的属性文字的字体大小
        //            attr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, 1))
        //
        //            // 4. 让textView显示 NSAttributedString
        //            // 取到光标
        //            var selectedRange = textView.selectedRange
        //
        //            // 把表情图片对应的attr添加到原来已经有的attr里面去
        //            // originalAttr.insertAttributedString(attr, atIndex: selectedRange.location)
        //            originalAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
        //            textView.attributedText = originalAttr
        //            // 将location加1
        //            selectedRange.location++
        //            // 将选中的长度改成0,以便在用户选中某段字符的时候,输入表情之后还会选中一段字符
        //            selectedRange.length = 0
        //            textView.selectedRange = selectedRange
        //            
        //        }else{
        //            // 是emoji
        //            textView.insertText((emoticon.code! as NSString).emoji())
        //        }
        
    }
    

    

    @objc private func willChangeFrame(noti: NSNotification) {

        // 不抖动
        if isToolBarAnimation == false {
            return
        }
        
        // 在这里拿到键盘的最终frame和动画持续的时间，根据这两个值，来修改自身tabBar控件的约束，随着键盘向上移动
        let overFrame =  (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"]! as! NSValue).CGRectValue()
        let overTime = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        
        composeTabBar.snp_updateConstraints { (make) in
            
            // 更新底部约束
             make.bottom.equalTo(overFrame.origin.y - SCREENH)
            
        }
        // TODO: WHY?
        UIView.animateWithDuration(overTime) { 
            
            self.composeTabBar.layoutIfNeeded()
        }
        
        
    }
    
    
    // NavgationItem的返回弹出按钮
    @objc private func fanhui() {
        
        dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    
    // MARK: -懒加载
    private lazy var rightItemBtn: UIButton = {
       
        let button = UIButton()
        button.addTarget(self, action: #selector(HMComposeViewController.send), forControlEvents: UIControlEvents.TouchUpInside)
        // 设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        // 设置不同状态下文字颜色
        button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Disabled)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        // 设置文字
        button.setTitle("发送", forState: UIControlState.Normal)
        // 设置字体大小
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        // 设置按钮的大小
        button.frame.size = CGSize(width: 40, height: 34)
        return button
        
    }()
    
    // Item的TitleView文字样式
    private lazy var titleItemView: UILabel = {
        
       let lbl = UILabel()
        // 拿到用户名字
       let screenName = (HMUserLoginViewModel.sharedUserLoginViewModel.account?.screen_name)!
        
        lbl.numberOfLines = 0
        lbl.textAlignment = .Center
        let str = "发微博\n\(screenName)"
        let attrString = NSMutableAttributedString(string: str)
        let attrDict = [
            NSForegroundColorAttributeName: UIColor.lightGrayColor(),
            NSFontAttributeName: UIFont.systemFontOfSize(14),
            NSStrokeWidthAttributeName: 2,
            NSStrokeColorAttributeName: UIColor.redColor()
        ]
        // 求出昵称所在的范围
        let range = (str as NSString).rangeOfString(screenName)
        // 添加属性
        attrString.addAttributes(attrDict, range: range)
        // 设置属性文字
        lbl.attributedText = attrString
        lbl.sizeToFit()
        return lbl
        
        
    }()
    
    // 发微博文字样式
    private lazy var textView: HMComposeTextView = {
        
        let textView = HMComposeTextView(frame: CGRectZero, textContainer: nil)
        textView.delegate = self
        textView.alwaysBounceVertical = true
        textView.placeholder = "奥运会期间马蓉获得了一块儿淫牌，奥运会期间马蓉获得了一块儿淫牌~~~~~"
        textView.font = UIFont.systemFontOfSize(15)
        return textView
    }()
    
    
    // MARK: -选择图片
    private func selectedPicture(){
        
        pictureView.hidden = false
        let vc = UIImagePickerController()
        // 设置成为代理,为了取得点击之后的图片
        vc.delegate = self
//         1. 判断照相机是否可用
        if UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Front) {
        // 指定数据来源的类型
        vc.sourceType = .Camera
        }
        
         UIImagePickerController.isSourceTypeAvailable(.Camera)
//         设置是否可以编译
         vc.allowsEditing = true
        self.presentViewController(vc, animated: true, completion: nil)
    }
    
    // MARK - 选择表情键盘
    private func selectedEmoticonKeyboard() {
        
        // 如果当前是系统键盘,就切换成表情键盘
        if textView.inputView == nil {
            // 设置textView.inputView
            textView.inputView = emoticonView
            composeTabBar.isSystemKeyboard = false
        }else{
            // 当前是表情键盘,就切换成系统键盘
            textView.inputView = nil
            composeTabBar.isSystemKeyboard = true
        }
        
        isToolBarAnimation = false
        // 取消第一响应者,会发送键盘frame改变的通知,由于我们监听过此通知,所以composetoolBar会执行一个0.25秒的往下的动画,而在0.25秒的动画还没有执行完毕的时候,我们又成为了第一响应者,这个时候又发送了一个键盘frame改变的通知,所以就造成抖动,解决方法就是,第一次取消第一响应的时候不需要去执行动画.
        textView.resignFirstResponder()
        
        
        isToolBarAnimation = true        // 成为第一响应者
        textView.becomeFirstResponder()
        
    }
    
    
    // MARK: - 监听方法
    
    /// 发送微博的方法
    @objc private func send(){
        
        if pictureView.images.count > 0 {
            // 发表图片微博
            upload()
        }else{
            // 发表文字微博
            update()
        }
    }
    
    /// 发表图片微博
    private func upload(){
        // 判断 accessToken 是否有值
        
        HMNetworkTools.sharedTools.upload(textView.emoticonText, image: pictureView.images.first!) { (responseObject, error) -> () in
            if error != nil {
                print("发表失败\(error)")
                SVProgressHUD.showErrorWithStatus("发表失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发表成功")
        }
        
        //        guard let accessToken = HMUserAccountViewModel.sharedAccountViewModel.accessToken else {
        //            print("accessToken不存在")
        //            return
        //        }
        
        //        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        //
        //        let parameters = [
        //            "access_token" :accessToken,
        //            "status": textView.emoticonText
        //        ]
        //
        //        let manager = AFHTTPSessionManager()
        //
        //        manager.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
        //
        //            let image = self.pictureView.images.first!
        //            let data = UIImagePNGRepresentation(image)!
        //            // 拼接图片数据需要的闭包
        //            /**
        //                - 参数1:name -> 接口里面对应该文件的字段
        //                - 参数2:fileName ->
        //                - 参数3:mimeType --> 告诉后台我要传给你的文件是什么类型的
        //                    - 大类型/小类型
        //                    - image/png text/html text/json
        //                    - 如果不知道是什么类型的话: application/octet-stream
        //            */
        //            formdata.appendPartWithFileData(data, name: "pic", fileName: "aabb", mimeType: "application/octet-stream")
        //
        //        }, progress: nil, success: { (_, responseObject) -> Void in
        //            // 请求成功要回调的闭包
        //            SVProgressHUD.showSuccessWithStatus("发表成功")
        //        }) { (_, error) -> Void in
        //            // 请求失败要回调的闭包
        //            SVProgressHUD.showErrorWithStatus("发表失败")
        //        }
    }
    
    /// 发表文字微博
    private func update(){
        HMNetworkTools.sharedTools.update(textView.emoticonText) { (responseObject, error) -> () in
            if error != nil {
                print("发表失败\(error)")
                SVProgressHUD.showErrorWithStatus("发表失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发表成功")
        }
    }

    
    
    // 底部自定义的bar
    private lazy var composeTabBar: HMStackView = {
        
        let compose = HMStackView(frame: CGRectZero)
        
        compose.composeCallBack = { (type: HMStackViewModel) in
            
            switch type {
            case .Picture:
                // 选择图片
                self.selectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                 self.selectedEmoticonKeyboard()
            case .Add:
                print("加号")
            }
        }
        return compose
        
    }()
    
    // 微博文字下面的配图
    private lazy var pictureView: HMComposePictuerView = {
       
        let pictureView = HMComposePictuerView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        
        pictureView.selectedPictureClosure = {
            
            self.selectedPicture()
            
        }
        return pictureView
        
    }()
    
    // 设置Emjo自定义表情键盘
    private lazy var emoticonView: HMEmoticonKeyboardView = {
       
        let em = HMEmoticonKeyboardView()
        
        em.frame = CGRectMake(0, 0, SCREENW, 224)
        
        return em
        
    }()

}

extension HMComposeViewController : UITextViewDelegate {
    
    // 当改变的时候
    func textViewDidChange(textView: UITextView) {
        // 设置右边按钮的可用状态
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 滑动时候关闭键盘
        self.textView.endEditing(true)
    }
    
    
}

// MARK: - 图片选择的控制器的代理方法
extension HMComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        picker.dismissViewControllerAnimated(true, completion: nil)
        // 调用配图控件的addImage的方法就可以了
        pictureView.addImage(image.scaleToWidth(600))
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        print("用户取消,可以在此弹出一个AlertView,在用户点击之后去执行下面这一行代码")
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

